home *** CD-ROM | disk | FTP | other *** search
/ Almathera Ten Pack 3: CDPD 3 / Almathera Ten on Ten - Disc 3: CDPD3.iso / fish / 001-100 / 001-025 / 006 / compress / compress.c < prev    next >
C/C++ Source or Header  |  1995-03-17  |  40KB  |  1,538 lines

  1. /* 
  2.  * Compress - data compression program 
  3.  */
  4.  
  5. /*
  6.  * machine variants which require cc -Dmachine:  pdp11, z8000, pcxt
  7.  */
  8.  
  9. /*
  10.  * Set USERMEM to the maximum amount of physical user memory available
  11.  * in bytes.  USERMEM is used to determine the maximum BITS that can be used
  12.  * for compression.
  13.  *
  14.  * SACREDMEM is the amount of physical memory saved for others; compress
  15.  * will hog the rest.
  16.  */
  17. #ifndef SACREDMEM
  18. #define SACREDMEM    0
  19. #endif
  20.  
  21. #ifndef USERMEM
  22. # ifdef AMIGA
  23. #   define USERMEM    200000
  24. # else
  25. #   define USERMEM     450000    /* default user memory */
  26. # endif
  27. #endif
  28.  
  29. #ifdef interdata        /* (Perkin-Elmer) */
  30. #define SIGNED_COMPARE_SLOW    /* signed compare is slower than unsigned */
  31. #endif
  32.  
  33. #ifdef pdp11
  34. # define BITS     12    /* max bits/code for 16-bit machine */
  35. # define NO_UCHAR    /* also if "unsigned char" functions as signed char */
  36. # undef USERMEM 
  37. #endif /* pdp11 */    /* don't forget to compile with -i */
  38.  
  39. #ifdef z8000
  40. # define BITS     12
  41. # undef vax        /* weird preprocessor */
  42. # undef USERMEM 
  43. #endif /* z8000 */
  44.  
  45. #ifdef pcxt
  46. # define BITS   12
  47. # undef USERMEM
  48. #endif /* pcxt */
  49.  
  50. #ifdef USERMEM
  51. # if USERMEM >= (433484+SACREDMEM)
  52. #  define PBITS    16
  53. # else
  54. #  if USERMEM >= (229600+SACREDMEM)
  55. #   define PBITS    15
  56. #  else
  57. #   if USERMEM >= (127536+SACREDMEM)
  58. #    define PBITS    14
  59. #   else
  60. #    if USERMEM >= (73464+SACREDMEM)
  61. #     define PBITS    13
  62. #    else
  63. #     define PBITS    12
  64. #    endif
  65. #   endif
  66. #  endif
  67. # endif
  68. # undef USERMEM
  69. #endif /* USERMEM */
  70.  
  71. #ifdef PBITS        /* Preferred BITS for this memory size */
  72. # ifndef BITS
  73. #  define BITS PBITS
  74. # endif BITS
  75. #endif /* PBITS */
  76.  
  77. #if BITS == 16
  78. # define HSIZE    69001        /* 95% occupancy */
  79. #endif
  80. #if BITS == 15
  81. # define HSIZE    35023        /* 94% occupancy */
  82. #endif
  83. #if BITS == 14
  84. # define HSIZE    18013        /* 91% occupancy */
  85. #endif
  86. #if BITS == 13
  87. # define HSIZE    9001        /* 91% occupancy */
  88. #endif
  89. #if BITS <= 12
  90. # define HSIZE    5003        /* 80% occupancy */
  91. #endif
  92.  
  93. #ifdef M_XENIX            /* Stupid compiler can't handle arrays with */
  94. # if BITS == 16            /* more than 65535 bytes - so we fake it */
  95. #  define XENIX_16
  96. # else
  97. #  if BITS > 13            /* Code only handles BITS = 12, 13, or 16 */
  98. #   define BITS    13
  99. #  endif
  100. # endif
  101. #endif
  102.  
  103. /*
  104.  * a code_int must be able to hold 2**BITS values of type int, and also -1
  105.  */
  106. #if BITS > 15
  107. typedef long int    code_int;
  108. #else
  109. typedef int        code_int;
  110. #endif
  111.  
  112. #ifdef SIGNED_COMPARE_SLOW
  113. typedef unsigned long int count_int;
  114. typedef unsigned short int count_short;
  115. #else
  116. typedef long int      count_int;
  117. #endif
  118.  
  119. #ifdef NO_UCHAR
  120.  typedef char    char_type;
  121. #else
  122.  typedef    unsigned char    char_type;
  123. #endif /* UCHAR */
  124. char_type magic_header[] = { "\037\235" };    /* 1F 9D */
  125.  
  126. /* Defines for third byte of header */
  127. #define BIT_MASK    0x1f
  128. #define BLOCK_MASK    0x80
  129. /* Masks 0x40 and 0x20 are free.  I think 0x20 should mean that there is
  130.    a fourth header byte (for expansion).
  131. */
  132. #define INIT_BITS 9            /* initial number of bits/code */
  133.  
  134. /*
  135.  * compress.c - File compression ala IEEE Computer, June 1984.
  136.  *
  137.  * Authors:    Spencer W. Thomas    (decvax!harpo!utah-cs!utah-gr!thomas)
  138.  *        Jim McKie        (decvax!mcvax!jim)
  139.  *        Steve Davies        (decvax!vax135!petsd!peora!srd)
  140.  *        Ken Turkowski        (decvax!decwrl!turtlevax!ken)
  141.  *        James A. Woods        (decvax!ihnp4!ames!jaw)
  142.  *        Joe Orost        (decvax!vax135!petsd!joe)
  143.  *
  144.  * $Header: compress.c,v 4.0 85/07/30 12:50:00 joe Release $
  145.  * $Log:    compress.c,v $
  146.  * Revision 4.0  85/07/30  12:50:00  joe
  147.  * Removed ferror() calls in output routine on every output except first.
  148.  * Prepared for release to the world.
  149.  * 
  150.  * Revision 3.6  85/07/04  01:22:21  joe
  151.  * Remove much wasted storage by overlaying hash table with the tables
  152.  * used by decompress: tab_suffix[1<<BITS], stack[8000].  Updated USERMEM
  153.  * computations.  Fixed dump_tab() DEBUG routine.
  154.  *
  155.  * Revision 3.5  85/06/30  20:47:21  jaw
  156.  * Change hash function to use exclusive-or.  Rip out hash cache.  These
  157.  * speedups render the megamemory version defunct, for now.  Make decoder
  158.  * stack global.  Parts of the RCS trunks 2.7, 2.6, and 2.1 no longer apply.
  159.  *
  160.  * Revision 3.4  85/06/27  12:00:00  ken
  161.  * Get rid of all floating-point calculations by doing all compression ratio
  162.  * calculations in fixed point.
  163.  *
  164.  * Revision 3.3  85/06/24  21:53:24  joe
  165.  * Incorporate portability suggestion for M_XENIX.  Got rid of text on #else
  166.  * and #endif lines.  Cleaned up #ifdefs for vax and interdata.
  167.  *
  168.  * Revision 3.2  85/06/06  21:53:24  jaw
  169.  * Incorporate portability suggestions for Z8000, IBM PC/XT from mailing list.
  170.  * Default to "quiet" output (no compression statistics).
  171.  *
  172.  * Revision 3.1  85/05/12  18:56:13  jaw
  173.  * Integrate decompress() stack speedups (from early pointer mods by McKie).
  174.  * Repair multi-file USERMEM gaffe.  Unify 'force' flags to mimic semantics
  175.  * of SVR2 'pack'.  Streamline block-compress table clear logic.  Increase 
  176.  * output byte count by magic number size.
  177.  * 
  178.  * Revision 3.0   84/11/27  11:50:00  petsd!joe
  179.  * Set HSIZE depending on BITS.  Set BITS depending on USERMEM.  Unrolled
  180.  * loops in clear routines.  Added "-C" flag for 2.0 compatibility.  Used
  181.  * unsigned compares on Perkin-Elmer.  Fixed foreground check.
  182.  *
  183.  * Revision 2.7   84/11/16  19:35:39  ames!jaw
  184.  * Cache common hash codes based on input statistics; this improves
  185.  * performance for low-density raster images.  Pass on #ifdef bundle
  186.  * from Turkowski.
  187.  *
  188.  * Revision 2.6   84/11/05  19:18:21  ames!jaw
  189.  * Vary size of hash tables to reduce time for small files.
  190.  * Tune PDP-11 hash function.
  191.  *
  192.  * Revision 2.5   84/10/30  20:15:14  ames!jaw
  193.  * Junk chaining; replace with the simpler (and, on the VAX, faster)
  194.  * double hashing, discussed within.  Make block compression standard.
  195.  *
  196.  * Revision 2.4   84/10/16  11:11:11  ames!jaw
  197.  * Introduce adaptive reset for block compression, to boost the rate
  198.  * another several percent.  (See mailing list notes.)
  199.  *
  200.  * Revision 2.3   84/09/22  22:00:00  petsd!joe
  201.  * Implemented "-B" block compress.  Implemented REVERSE sorting of tab_next.
  202.  * Bug fix for last bits.  Changed fwrite to putchar loop everywhere.
  203.  *
  204.  * Revision 2.2   84/09/18  14:12:21  ames!jaw
  205.  * Fold in news changes, small machine typedef from thomas,
  206.  * #ifdef interdata from joe.
  207.  *
  208.  * Revision 2.1   84/09/10  12:34:56  ames!jaw
  209.  * Configured fast table lookup for 32-bit machines.
  210.  * This cuts user time in half for b <= FBITS, and is useful for news batching
  211.  * from VAX to PDP sites.  Also sped up decompress() [fwrite->putc] and
  212.  * added signal catcher [plus beef in writeerr()] to delete effluvia.
  213.  *
  214.  * Revision 2.0   84/08/28  22:00:00  petsd!joe
  215.  * Add check for foreground before prompting user.  Insert maxbits into
  216.  * compressed file.  Force file being uncompressed to end with ".Z".
  217.  * Added "-c" flag and "zcat".  Prepared for release.
  218.  *
  219.  * Revision 1.10  84/08/24  18:28:00  turtlevax!ken
  220.  * Will only compress regular files (no directories), added a magic number
  221.  * header (plus an undocumented -n flag to handle old files without headers),
  222.  * added -f flag to force overwriting of possibly existing destination file,
  223.  * otherwise the user is prompted for a response.  Will tack on a .Z to a
  224.  * filename if it doesn't have one when decompressing.  Will only replace
  225.  * file if it was compressed.
  226.  *
  227.  * Revision 1.9  84/08/16  17:28:00  turtlevax!ken
  228.  * Removed scanargs(), getopt(), added .Z extension and unlimited number of
  229.  * filenames to compress.  Flags may be clustered (-Ddvb12) or separated
  230.  * (-D -d -v -b 12), or combination thereof.  Modes and other status is
  231.  * copied with copystat().  -O bug for 4.2 seems to have disappeared with
  232.  * 1.8.
  233.  *
  234.  * Revision 1.8  84/08/09  23:15:00  joe
  235.  * Made it compatible with vax version, installed jim's fixes/enhancements
  236.  *
  237.  * Revision 1.6  84/08/01  22:08:00  joe
  238.  * Sped up algorithm significantly by sorting the compress chain.
  239.  *
  240.  * Revision 1.5  84/07/13  13:11:00  srd
  241.  * Added C version of vax asm routines.  Changed structure to arrays to
  242.  * save much memory.  Do unsigned compares where possible (faster on
  243.  * Perkin-Elmer)
  244.  *
  245.  * Revision 1.4  84/07/05  03:11:11  thomas
  246.  * Clean up the code a little and lint it.  (Lint complains about all
  247.  * the regs used in the asm, but I'm not going to "fix" this.)
  248.  *
  249.  * Revision 1.3  84/07/05  02:06:54  thomas
  250.  * Minor fixes.
  251.  *
  252.  * Revision 1.2  84/07/05  00:27:27  thomas
  253.  * Add variable bit length output.
  254.  *
  255.  */
  256. static char rcs_ident[] = "$Header: compress.c,v 4.0 85/07/30 12:50:00 joe Release $";
  257.  
  258. #include <stdio.h>
  259. #include <ctype.h>
  260. #ifdef unix
  261. #include <signal.h>
  262. #include <sys/types.h>
  263. #include <sys/stat.h>
  264. #endif
  265.  
  266. #ifndef min
  267. #define    min(a,b)    ((a>b) ? b : a)
  268. #endif
  269.  
  270. #define ARGVAL() (*++(*argv) || (--argc && *++argv))
  271.  
  272. int n_bits;                /* number of bits/code */
  273. int maxbits = BITS;            /* user settable max # bits/code */
  274. code_int maxcode;            /* maximum code, given n_bits */
  275. code_int maxmaxcode = 1 << BITS;    /* should NEVER generate this code */
  276. #ifdef COMPATIBLE        /* But wrong! */
  277. # define MAXCODE(n_bits)    (1 << (n_bits) - 1)
  278. #else
  279. # define MAXCODE(n_bits)    ((1 << (n_bits)) - 1)
  280. #endif /* COMPATIBLE */
  281.  
  282. #ifdef XENIX_16
  283. count_int htab0[8192];
  284. count_int htab1[8192];
  285. count_int htab2[8192];
  286. count_int htab3[8192];
  287. count_int htab4[8192];
  288. count_int htab5[8192];
  289. count_int htab6[8192];
  290. count_int htab7[8192];
  291. count_int htab8[HSIZE-65536];
  292. count_int * htab[9] = {
  293.     htab0, htab1, htab2, htab3, htab4, htab5, htab6, htab7, htab8 };
  294.  
  295. #define htabof(i)    (htab[(i) >> 13][(i) & 0x1fff])
  296. unsigned short code0tab[16384];
  297. unsigned short code1tab[16384];
  298. unsigned short code2tab[16384];
  299. unsigned short code3tab[16384];
  300. unsigned short code4tab[16384];
  301. unsigned short * codetab[5] = {
  302.     code0tab, code1tab, code2tab, code3tab, code4tab };
  303.  
  304. #define codetabof(i)    (codetab[(i) >> 14][(i) & 0x3fff])
  305.  
  306. #else    /* Normal machine */
  307. count_int htab [HSIZE];
  308. unsigned short codetab [HSIZE];
  309. #define htabof(i)    htab[i]
  310. #define codetabof(i)    codetab[i]
  311. #endif    /* XENIX_16 */
  312. code_int hsize = HSIZE;            /* for dynamic table sizing */
  313. count_int fsize;
  314.  
  315. /*
  316.  * To save much memory, we overlay the table used by compress() with those
  317.  * used by decompress().  The tab_prefix table is the same size and type
  318.  * as the codetab.  The tab_suffix table needs 2**BITS characters.  We
  319.  * get this from the beginning of htab.  The output stack uses the rest
  320.  * of htab, and contains characters.  There is plenty of room for any
  321.  * possible stack (stack used to be 8000 characters).
  322.  */
  323.  
  324. #define tab_prefixof(i)    codetabof(i)
  325. #ifdef XENIX_16
  326. # define tab_suffixof(i)    ((char_type *)htab[(i)>>15])[(i) & 0x7fff]
  327. # define de_stack        ((char_type *)(htab2))
  328. #else    /* Normal machine */
  329. # define tab_suffixof(i)    ((char_type *)(htab))[i]
  330. # define de_stack        ((char_type *)&tab_suffixof(1<<BITS))
  331. #endif    /* XENIX_16 */
  332.  
  333. code_int free_ent = 0;            /* first unused entry */
  334. int exit_stat = 0;
  335.  
  336. code_int getcode();
  337.  
  338. Usage() {
  339. #ifdef DEBUG
  340. fprintf(stderr,"Usage: compress [-dDVfc] [-b maxbits] [file ...]\n");
  341. }
  342. int debug = 0;
  343. #else
  344. fprintf(stderr,"Usage: compress [-dfvcV] [-b maxbits] [file ...]\n");
  345. }
  346. #endif /* DEBUG */
  347. int nomagic = 0;    /* Use a 3-byte magic number header, unless old file */
  348. int zcat_flg = 0;    /* Write output on stdout, suppress messages */
  349. int quiet = 1;        /* don't tell me about compression */
  350.  
  351. /*
  352.  * block compression parameters -- after all codes are used up,
  353.  * and compression rate changes, start over.
  354.  */
  355. int block_compress = BLOCK_MASK;
  356. int clear_flg = 0;
  357. long int ratio = 0;
  358. #define CHECK_GAP 10000    /* ratio check interval */
  359. count_int checkpoint = CHECK_GAP;
  360. /*
  361.  * the next two codes should not be changed lightly, as they must not
  362.  * lie within the contiguous general code space.
  363.  */ 
  364. #define FIRST    257    /* first free entry */
  365. #define    CLEAR    256    /* table clear output code */
  366.  
  367. int force = 0;
  368. char ofname [100];
  369. #ifdef DEBUG
  370. int verbose = 0;
  371. #endif /* DEBUG */
  372. int (*bgnd_flag)();
  373.  
  374. int do_decomp = 0;
  375.  
  376. static void decompress ();
  377. static void compress ();
  378.  
  379. /*****************************************************************
  380.  * TAG( main )
  381.  *
  382.  * Algorithm from "A Technique for High Performance Data Compression",
  383.  * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
  384.  *
  385.  * Usage: compress [-dfvc] [-b bits] [file ...]
  386.  * Inputs:
  387.  *    -d:        If given, decompression is done instead.
  388.  *
  389.  *      -c:         Write output on stdout, don't remove original.
  390.  *
  391.  *      -b:         Parameter limits the max number of bits/code.
  392.  *
  393.  *    -f:        Forces output file to be generated, even if one already
  394.  *            exists, and even if no space is saved by compressing.
  395.  *            If -f is not used, the user will be prompted if stdin is
  396.  *            a tty, otherwise, the output file will not be overwritten.
  397.  *
  398.  *      -v:        Write compression statistics
  399.  *
  400.  *     file ...:   Files to be compressed.  If none specified, stdin
  401.  *            is used.
  402.  * Outputs:
  403.  *    file.Z:        Compressed form of file with same mode, owner, and utimes
  404.  *     or stdout   (if stdin used as input)
  405.  *
  406.  * Assumptions:
  407.  *    When filenames are given, replaces with the compressed version
  408.  *    (.Z suffix) only if the file decreases in size.
  409.  * Algorithm:
  410.  *     Modified Lempel-Ziv method (LZW).  Basically finds common
  411.  * substrings and replaces them with a variable size code.  This is
  412.  * deterministic, and can be done on the fly.  Thus, the decompression
  413.  * procedure needs no input table, but tracks the way the table was built.
  414.  */
  415.  
  416. main( argc, argv )
  417. register int argc; char **argv;
  418. {
  419.     int overwrite = 0;    /* Do not overwrite unless given -f flag */
  420.     char tempname[100];
  421.     char **filelist, **fileptr;
  422.     char *cp, *rindex(), *malloc();
  423.     extern onintr(), oops();
  424.  
  425.  
  426. #ifdef unix
  427.     if ( (bgnd_flag = signal ( SIGINT, SIG_IGN )) != SIG_IGN ) {
  428.     signal ( SIGINT, onintr );
  429.     signal ( SIGSEGV, oops );
  430.     }
  431. #endif
  432.  
  433. #ifdef COMPATIBLE
  434.     nomagic = 1;    /* Original didn't have a magic number */
  435. #endif /* COMPATIBLE */
  436.  
  437.     filelist = fileptr = (char **)(malloc(argc * sizeof(*argv)));
  438.     *filelist = NULL;
  439.  
  440.     if((cp = rindex(argv[0], '/')) != 0) {
  441.     cp++;
  442.     } else {
  443.     cp = argv[0];
  444.     }
  445.     if(strcmp(cp, "uncompress") == 0) {
  446.     do_decomp = 1;
  447.     } else if(strcmp(cp, "zcat") == 0) {
  448.     do_decomp = 1;
  449.     zcat_flg = 1;
  450.     }
  451.  
  452. #ifdef BSD4_2
  453.     /* 4.2BSD dependent - take it out if not */
  454.     setlinebuf( stderr );
  455. #endif /* BSD4_2 */
  456.  
  457.     /* Argument Processing
  458.      * All flags are optional.
  459.      * -D => debug
  460.      * -V => print Version; debug verbose
  461.      * -d => do_decomp
  462.      * -v => unquiet
  463.      * -f => force overwrite of output file
  464.      * -n => no header: useful to uncompress old files
  465.      * -b maxbits => maxbits.  If -b is specified, then maxbits MUST be
  466.      *        given also.
  467.      * -c => cat all output to stdout
  468.      * -C => generate output compatible with compress 2.0.
  469.      * if a string is left, must be an input filename.
  470.      */
  471.     for (argc--, argv++; argc > 0; argc--, argv++) {
  472.     if (**argv == '-') {    /* A flag argument */
  473.         while (*++(*argv)) {    /* Process all flags in this arg */
  474.         switch (**argv) {
  475. #ifdef DEBUG
  476.             case 'D':
  477.             debug = 1;
  478.             break;
  479.             case 'V':
  480.             verbose = 1;
  481.             version();
  482.             break;
  483. #else
  484.             case 'V':
  485.             version();
  486.             break;
  487. #endif /* DEBUG */
  488.             case 'v':
  489.             quiet = 0;
  490.             break;
  491.             case 'd':
  492.             do_decomp = 1;
  493.             break;
  494.             case 'f':
  495.             case 'F':
  496.             overwrite = 1;
  497.             force = 1;
  498.             break;
  499.             case 'n':
  500.             nomagic = 1;
  501.             break;
  502.             case 'C':
  503.             block_compress = 0;
  504.             break;
  505.             case 'b':
  506.             if (!ARGVAL()) {
  507.                 fprintf(stderr, "Missing maxbits\n");
  508.                 Usage();
  509.                 exit(1);
  510.             }
  511.             maxbits = atoi(*argv);
  512.             goto nextarg;
  513.             case 'c':
  514.             zcat_flg = 1;
  515.             break;
  516.             case 'q':
  517.             quiet = 1;
  518.             break;
  519.             default:
  520.             fprintf(stderr, "Unknown flag: '%c'; ", **argv);
  521.             Usage();
  522.             exit(1);
  523.         }
  524.         }
  525.     }
  526.     else {        /* Input file name */
  527.         *fileptr++ = *argv;    /* Build input file list */
  528.         *fileptr = NULL;
  529.         /* process nextarg; */
  530.     }
  531.     nextarg: continue;
  532.     }
  533.  
  534.     if(maxbits < INIT_BITS) maxbits = INIT_BITS;
  535.     if (maxbits > BITS) maxbits = BITS;
  536.     maxmaxcode = 1 << maxbits;
  537.  
  538.     if (*filelist != NULL) {
  539.     for (fileptr = filelist; *fileptr; fileptr++) {
  540.         exit_stat = 0;
  541.         if (do_decomp != 0) {            /* DECOMPRESSION */
  542.         /* Check for .Z suffix */
  543.         if (strcmp(*fileptr + strlen(*fileptr) - 2, ".Z") != 0) {
  544.             /* No .Z: tack one on */
  545.             strcpy(tempname, *fileptr);
  546.             strcat(tempname, ".Z");
  547.             *fileptr = tempname;
  548.         }
  549.         /* Open input file */
  550.         if ((freopen(*fileptr, "r", stdin)) == NULL) {
  551.             perror(*fileptr); continue;
  552.         }
  553.         /* Check the magic number */
  554.         if (nomagic == 0) {
  555.             if ((getchar() != (magic_header[0] & 0xFF))
  556.              || (getchar() != (magic_header[1] & 0xFF))) {
  557.             fprintf(stderr, "%s: not in compressed format\n",
  558.                 *fileptr);
  559.             continue;
  560.             }
  561.             maxbits = getchar();    /* set -b from file */
  562.             block_compress = maxbits & BLOCK_MASK;
  563.             maxbits &= BIT_MASK;
  564.             maxmaxcode = 1 << maxbits;
  565.             if(maxbits > BITS) {
  566.             fprintf(stderr,
  567.             "%s: compressed with %d bits, can only handle %d bits\n",
  568.             *fileptr, maxbits, BITS);
  569.             continue;
  570.             }
  571.         }
  572.         /* Generate output filename */
  573.         strcpy(ofname, *fileptr);
  574.         ofname[strlen(*fileptr) - 2] = '\0';  /* Strip off .Z */
  575.         } else {                    /* COMPRESSION */
  576.         if (strcmp(*fileptr + strlen(*fileptr) - 2, ".Z") == 0) {
  577.                 fprintf(stderr, "%s: already has .Z suffix -- no change\n",
  578.                 *fileptr);
  579.             continue;
  580.         }
  581.         /* Open input file */
  582.         if ((freopen(*fileptr, "r", stdin)) == NULL) {
  583.             perror(*fileptr); continue;
  584.         }
  585.         fsize = getfilesize (*fileptr);
  586.         /*
  587.          * tune hash table size for small files -- ad hoc,
  588.          * but the sizes match earlier #defines, which
  589.          * serve as upper bounds on the number of output codes. 
  590.          */
  591.         hsize = HSIZE;
  592.         if ( fsize < (1 << 12) )
  593.             hsize = min ( 5003, HSIZE );
  594.         else if ( fsize < (1 << 13) )
  595.             hsize = min ( 9001, HSIZE );
  596.         else if ( fsize < (1 << 14) )
  597.             hsize = min ( 18013, HSIZE );
  598.         else if ( fsize < (1 << 15) )
  599.             hsize = min ( 35023, HSIZE );
  600.         else if ( fsize < 47000 )
  601.             hsize = min ( 50021, HSIZE );
  602.  
  603.         /* Generate output filename */
  604.         strcpy(ofname, *fileptr);
  605. #ifndef BSD4_2        /* Short filenames */
  606.         if ((cp=rindex(ofname,'/')) != NULL)    cp++;
  607.         else                    cp = ofname;
  608.         if (strlen(cp) > 12) {
  609.             fprintf(stderr,"%s: filename too long to tack on .Z\n",cp);
  610.             continue;
  611.         }
  612. #endif  /* BSD4_2        Long filenames allowed */
  613.         strcat(ofname, ".Z");
  614.         }
  615.         /* Check for overwrite of existing file */
  616. #ifdef unix
  617.         if (overwrite == 0 && zcat_flg == 0) {
  618.         if (stat(ofname, &statbuf) == 0) {
  619.             char response[2];
  620.             response[0] = 'n';
  621.             fprintf(stderr, "%s already exists;", ofname);
  622.             if (foreground()) {
  623.             fprintf(stderr, " do you wish to overwrite %s (y or n)? ",
  624.             ofname);
  625.             fflush(stderr);
  626.             read(2, response, 2);
  627.             while (response[1] != '\n') {
  628.                 if (read(2, response+1, 1) < 0) {    /* Ack! */
  629.                 perror("stderr"); break;
  630.                 }
  631.             }
  632.             }
  633.             if (response[0] != 'y') {
  634.             fprintf(stderr, "\tnot overwritten\n");
  635.             continue;
  636.             }
  637.         }
  638.         }
  639. #endif
  640.         if(zcat_flg == 0) {        /* Open output file */
  641.         if (freopen(ofname, "w", stdout) == NULL) {
  642.             perror(ofname);
  643.             continue;
  644.         }
  645.         if(!quiet)
  646.             fprintf(stderr, "%s: ", *fileptr);
  647.         }
  648.  
  649.         /* Actually do the compression/decompression */
  650.         if (do_decomp == 0)    compress();
  651. #ifndef DEBUG
  652.         else            decompress();
  653. #else
  654.         else if (debug == 0)    decompress();
  655.         else            printcodes();
  656.         if (verbose)        dump_tab();
  657. #endif /* DEBUG */
  658.         if(zcat_flg == 0) {
  659.         copystat(*fileptr, ofname);    /* Copy stats */
  660.         if((exit_stat == 1) || (!quiet))
  661.             putc('\n', stderr);
  662.         }
  663.     }
  664.     } else {        /* Standard input */
  665.     if (do_decomp == 0) {
  666.         compress();
  667. #ifdef DEBUG
  668.         if(verbose)        dump_tab();
  669. #endif /* DEBUG */
  670.         if(!quiet)
  671.             putc('\n', stderr);
  672.     } else {
  673.         /* Check the magic number */
  674.         if (nomagic == 0) {
  675.         if ((getchar()!=(magic_header[0] & 0xFF))
  676.          || (getchar()!=(magic_header[1] & 0xFF))) {
  677.             fprintf(stderr, "stdin: not in compressed format\n");
  678.             exit(1);
  679.         }
  680.         maxbits = getchar();    /* set -b from file */
  681.         block_compress = maxbits & BLOCK_MASK;
  682.         maxbits &= BIT_MASK;
  683.         maxmaxcode = 1 << maxbits;
  684.         fsize = 100000;        /* assume stdin large for USERMEM */
  685.         if(maxbits > BITS) {
  686.             fprintf(stderr,
  687.             "stdin: compressed with %d bits, can only handle %d bits\n",
  688.             maxbits, BITS);
  689.             exit(1);
  690.         }
  691.         }
  692. #ifndef DEBUG
  693.         decompress();
  694. #else
  695.         if (debug == 0)    decompress();
  696.         else        printcodes();
  697.         if (verbose)    dump_tab();
  698. #endif /* DEBUG */
  699.     }
  700.     }
  701.     exit(exit_stat);
  702. }
  703.  
  704. static int offset;
  705. long int in_count = 1;            /* length of input */
  706. long int bytes_out;            /* length of compressed output */
  707. long int out_count = 0;            /* # of codes output (for debugging) */
  708.  
  709. /*
  710.  * compress stdin to stdout
  711.  *
  712.  * Algorithm:  use open addressing double hashing (no chaining) on the 
  713.  * prefix code / next character combination.  We do a variant of Knuth's
  714.  * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  715.  * secondary probe.  Here, the modular division first probe is gives way
  716.  * to a faster exclusive-or manipulation.  Also do block compression with
  717.  * an adaptive reset, whereby the code table is cleared when the compression
  718.  * ratio decreases, but after the table fills.  The variable-length output
  719.  * codes are re-sized at this point, and a special CLEAR code is generated
  720.  * for the decompressor.  Late addition:  construct the table according to
  721.  * file size for noticeable speed improvement on small files.  Please direct
  722.  * questions about this implementation to ames!jaw.
  723.  */
  724.  
  725. static void compress() {
  726.     register long fcode;
  727.     register code_int i = 0;
  728.     register int c;
  729.     register code_int ent;
  730. #ifdef XENIX_16
  731.     register code_int disp;
  732. #else    /* Normal machine */
  733.     register int disp;
  734. #endif
  735.     register code_int hsize_reg;
  736.     register int hshift;
  737.  
  738. #ifndef COMPATIBLE
  739.     if (nomagic == 0) {
  740.     putchar(magic_header[0]); putchar(magic_header[1]);
  741.     putchar((char)(maxbits | block_compress));
  742.     if(ferror(stdout))
  743.         writeerr();
  744.     }
  745. #endif /* COMPATIBLE */
  746.  
  747.     offset = 0;
  748.     bytes_out = 3;        /* includes 3-byte header mojo */
  749.     out_count = 0;
  750.     clear_flg = 0;
  751.     ratio = 0;
  752.     in_count = 1;
  753.     checkpoint = CHECK_GAP;
  754.     maxcode = MAXCODE(n_bits = INIT_BITS);
  755.     free_ent = ((block_compress) ? FIRST : 256 );
  756.  
  757.     ent = getchar ();
  758.  
  759.     hshift = 0;
  760.     for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
  761.         hshift++;
  762.     hshift = 8 - hshift;        /* set hash code range bound */
  763.  
  764.     hsize_reg = hsize;
  765.     cl_hash( (count_int) hsize_reg);        /* clear hash table */
  766.  
  767. #ifdef SIGNED_COMPARE_SLOW
  768.     while ( (c = getchar()) != (unsigned) EOF ) {
  769. #else
  770.     while ( (c = getchar()) != EOF ) {
  771. #endif
  772.     in_count++;
  773.     fcode = (long) (((long) c << maxbits) + ent);
  774.      i = ((c << hshift) ^ ent);    /* xor hashing */
  775.  
  776.     if ( htabof (i) == fcode ) {
  777.         ent = codetabof (i);
  778.         continue;
  779.     } else if ( (long)htabof (i) < 0 )    /* empty slot */
  780.         goto nomatch;
  781.      disp = hsize_reg - i;        /* secondary hash (after G. Knott) */
  782.     if ( i == 0 )
  783.         disp = 1;
  784. probe:
  785.     if ( (i -= disp) < 0 )
  786.         i += hsize_reg;
  787.  
  788.     if ( htabof (i) == fcode ) {
  789.         ent = codetabof (i);
  790.         continue;
  791.     }
  792.     if ( (long)htabof (i) > 0 ) 
  793.         goto probe;
  794. nomatch:
  795.     output ( (code_int) ent );
  796.     out_count++;
  797.      ent = c;
  798. #ifdef SIGNED_COMPARE_SLOW
  799.     if ( (unsigned) free_ent < (unsigned) maxmaxcode) {
  800. #else
  801.     if ( free_ent < maxmaxcode ) {
  802. #endif
  803.          codetabof (i) = free_ent++;    /* code -> hashtable */
  804.         htabof (i) = fcode;
  805.     }
  806.     else if ( (count_int)in_count >= checkpoint && block_compress )
  807.         cl_block ();
  808.     }
  809.     /*
  810.      * Put out the final code.
  811.      */
  812.     output( (code_int)ent );
  813.     out_count++;
  814.     output( (code_int)-1 );
  815.  
  816.     /*
  817.      * Print out stats on stderr
  818.      */
  819.     if(zcat_flg == 0 && !quiet) {
  820. #ifdef DEBUG
  821.     fprintf( stderr,
  822.         "%ld chars in, %ld codes (%ld bytes) out, compression factor: ",
  823.         in_count, out_count, bytes_out );
  824.     prratio( stderr, in_count, bytes_out );
  825.     fprintf( stderr, "\n");
  826.     fprintf( stderr, "\tCompression as in compact: " );
  827.     prratio( stderr, in_count-bytes_out, in_count );
  828.     fprintf( stderr, "\n");
  829.     fprintf( stderr, "\tLargest code (of last block) was %d (%d bits)\n",
  830.         free_ent - 1, n_bits );
  831. #else /* !DEBUG */
  832.     fprintf( stderr, "Compression: " );
  833.     prratio( stderr, in_count-bytes_out, in_count );
  834. #endif /* DEBUG */
  835.     }
  836.     if(bytes_out > in_count)    /* exit(2) if no savings */
  837.     exit_stat = 2;
  838.     return;
  839. }
  840.  
  841. /*****************************************************************
  842.  * TAG( output )
  843.  *
  844.  * Output the given code.
  845.  * Inputs:
  846.  *     code:    A n_bits-bit integer.  If == -1, then EOF.  This assumes
  847.  *        that n_bits =< (long)wordsize - 1.
  848.  * Outputs:
  849.  *     Outputs code to the file.
  850.  * Assumptions:
  851.  *    Chars are 8 bits long.
  852.  * Algorithm:
  853.  *     Maintain a BITS character long buffer (so that 8 codes will
  854.  * fit in it exactly).  Use the VAX insv instruction to insert each
  855.  * code in turn.  When the buffer fills up empty it and start over.
  856.  */
  857.  
  858. static char buf[BITS];
  859.  
  860. #ifndef vax
  861. char_type lmask[9] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
  862. char_type rmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
  863. #endif /* vax */
  864.  
  865. output( code )
  866. code_int  code;
  867. {
  868. #ifdef DEBUG
  869.     static int col = 0;
  870. #endif /* DEBUG */
  871.  
  872.     /*
  873.      * On the VAX, it is important to have the register declarations
  874.      * in exactly the order given, or the asm will break.
  875.      */
  876.     register int r_off = offset, bits= n_bits;
  877.     register char * bp = buf;
  878.  
  879. #ifdef DEBUG
  880.     if ( verbose )
  881.         fprintf( stderr, "%5d%c", code,
  882.             (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  883. #endif /* DEBUG */
  884.     if ( code >= 0 ) {
  885. #ifdef vax
  886.     /* VAX DEPENDENT!! Implementation on other machines is below.
  887.      *
  888.      * Translation: Insert BITS bits from the argument starting at
  889.      * offset bits from the beginning of buf.
  890.      */
  891.     0;    /* Work around for pcc -O bug with asm and if stmt */
  892.     asm( "insv    4(ap),r11,r10,(r9)" );
  893. #else /* not a vax */
  894. /* 
  895.  * byte/bit numbering on the VAX is simulated by the following code
  896.  */
  897.     /*
  898.      * Get to the first byte.
  899.      */
  900.     bp += (r_off >> 3);
  901.     r_off &= 7;
  902.     /*
  903.      * Since code is always >= 8 bits, only need to mask the first
  904.      * hunk on the left.
  905.      */
  906.     *bp = (*bp & rmask[r_off]) | (code << r_off) & lmask[r_off];
  907.     bp++;
  908.     bits -= (8 - r_off);
  909.     code >>= 8 - r_off;
  910.     /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  911.     if ( bits >= 8 ) {
  912.         *bp++ = code;
  913.         code >>= 8;
  914.         bits -= 8;
  915.     }
  916.     /* Last bits. */
  917.     if(bits)
  918.         *bp = code;
  919. #endif /* vax */
  920.     offset += n_bits;
  921.     if ( offset == (n_bits << 3) ) {
  922.         bp = buf;
  923.         bits = n_bits;
  924.         bytes_out += bits;
  925.         do
  926.         putchar(*bp++);
  927.         while(--bits);
  928.         offset = 0;
  929.     }
  930.  
  931.     /*
  932.      * If the next entry is going to be too big for the code size,
  933.      * then increase it, if possible.
  934.      */
  935.     if ( free_ent > maxcode || (clear_flg > 0))
  936.     {
  937.         /*
  938.          * Write the whole buffer, because the input side won't
  939.          * discover the size increase until after it has read it.
  940.          */
  941.         if ( offset > 0 ) {
  942.         if( fwrite( buf, 1, n_bits, stdout ) != n_bits)
  943.             writeerr();
  944.         bytes_out += n_bits;
  945.         }
  946.         offset = 0;
  947.  
  948.         if ( clear_flg ) {
  949.                 maxcode = MAXCODE (n_bits = INIT_BITS);
  950.             clear_flg = 0;
  951.         }
  952.         else {
  953.             n_bits++;
  954.             if ( n_bits == maxbits )
  955.             maxcode = maxmaxcode;
  956.             else
  957.             maxcode = MAXCODE(n_bits);
  958.         }
  959. #ifdef DEBUG
  960.         if ( debug ) {
  961.         fprintf( stderr, "\nChange to %d bits\n", n_bits );
  962.         col = 0;
  963.         }
  964. #endif /* DEBUG */
  965.     }
  966.     } else {
  967.     /*
  968.      * At EOF, write the rest of the buffer.
  969.      */
  970.     if ( offset > 0 )
  971.         fwrite( buf, 1, (offset + 7) / 8, stdout );
  972.     bytes_out += (offset + 7) / 8;
  973.     offset = 0;
  974.     fflush( stdout );
  975. #ifdef DEBUG
  976.     if ( verbose )
  977.         fprintf( stderr, "\n" );
  978. #endif /* DEBUG */
  979.     if( ferror( stdout ) )
  980.         writeerr();
  981.     }
  982. }
  983.  
  984. /*
  985.  * Decompress stdin to stdout.  This routine adapts to the codes in the
  986.  * file building the "string" table on-the-fly; requiring no table to
  987.  * be stored in the compressed file.  The tables used herein are shared
  988.  * with those of the compress() routine.  See the definitions above.
  989.  */
  990.  
  991. static void decompress() {
  992.     register char_type *stackp;
  993.     register int finchar;
  994.     register code_int code, oldcode, incode;
  995.  
  996.     /*
  997.      * As above, initialize the first 256 entries in the table.
  998.      */
  999.     maxcode = MAXCODE(n_bits = INIT_BITS);
  1000.     for ( code = 255; code >= 0; code-- ) {
  1001.     tab_prefixof(code) = 0;
  1002.     tab_suffixof(code) = (char_type)code;
  1003.     }
  1004.     free_ent = ((block_compress) ? FIRST : 256 );
  1005.  
  1006.     finchar = oldcode = getcode();
  1007.     if(oldcode == -1)    /* EOF already? */
  1008.     return;            /* Get out of here */
  1009.     putchar( (char)finchar );        /* first code must be 8 bits = char */
  1010.     if(ferror(stdout))        /* Crash if can't write */
  1011.     writeerr();
  1012.     stackp = de_stack;
  1013.  
  1014.     while ( (code = getcode()) > -1 ) {
  1015.  
  1016.     if ( (code == CLEAR) && block_compress ) {
  1017.         for ( code = 255; code >= 0; code-- )
  1018.         tab_prefixof(code) = 0;
  1019.         clear_flg = 1;
  1020.         free_ent = FIRST - 1;
  1021.         if ( (code = getcode ()) == -1 )    /* O, untimely death! */
  1022.         break;
  1023.     }
  1024.     incode = code;
  1025.     /*
  1026.      * Special case for KwKwK string.
  1027.      */
  1028.     if ( code >= free_ent ) {
  1029.             *stackp++ = finchar;
  1030.         code = oldcode;
  1031.     }
  1032.  
  1033.     /*
  1034.      * Generate output characters in reverse order
  1035.      */
  1036. #ifdef SIGNED_COMPARE_SLOW
  1037.     while ( ((unsigned long)code) >= ((unsigned long)256) ) {
  1038. #else
  1039.     while ( code >= 256 ) {
  1040. #endif
  1041.         *stackp++ = tab_suffixof(code);
  1042.         code = tab_prefixof(code);
  1043.     }
  1044.     *stackp++ = finchar = tab_suffixof(code);
  1045.  
  1046.     /*
  1047.      * And put them out in forward order
  1048.      */
  1049.     do
  1050.         putchar ( *--stackp );
  1051.     while ( stackp > de_stack );
  1052.  
  1053.     /*
  1054.      * Generate the new entry.
  1055.      */
  1056.     if ( (code=free_ent) < maxmaxcode ) {
  1057.         tab_prefixof(code) = (unsigned short)oldcode;
  1058.         tab_suffixof(code) = finchar;
  1059.         free_ent = code+1;
  1060.     } 
  1061.     /*
  1062.      * Remember previous code.
  1063.      */
  1064.     oldcode = incode;
  1065.     }
  1066.     fflush( stdout );
  1067.     if(ferror(stdout))
  1068.     writeerr();
  1069. }
  1070.  
  1071. /*****************************************************************
  1072.  * TAG( getcode )
  1073.  *
  1074.  * Read one code from the standard input.  If EOF, return -1.
  1075.  * Inputs:
  1076.  *     stdin
  1077.  * Outputs:
  1078.  *     code or -1 is returned.
  1079.  */
  1080.  
  1081. code_int
  1082. getcode() {
  1083.     /*
  1084.      * On the VAX, it is important to have the register declarations
  1085.      * in exactly the order given, or the asm will break.
  1086.      */
  1087.     register code_int code;
  1088.     static int offset = 0, size = 0;
  1089.     static char_type buf[BITS];
  1090.     register int r_off, bits;
  1091.     register char_type *bp = buf;
  1092.  
  1093.     if ( clear_flg > 0 || offset >= size || free_ent > maxcode ) {
  1094.     /*
  1095.      * If the next entry will be too big for the current code
  1096.      * size, then we must increase the size.  This implies reading
  1097.      * a new buffer full, too.
  1098.      */
  1099.     if ( free_ent > maxcode ) {
  1100.         n_bits++;
  1101.         if ( n_bits == maxbits )
  1102.         maxcode = maxmaxcode;    /* won't get any bigger now */
  1103.         else
  1104.         maxcode = MAXCODE(n_bits);
  1105.     }
  1106.     if ( clear_flg > 0) {
  1107.             maxcode = MAXCODE (n_bits = INIT_BITS);
  1108.         clear_flg = 0;
  1109.     }
  1110.     size = fread( buf, 1, n_bits, stdin );
  1111.     if ( size <= 0 )
  1112.         return -1;            /* end of file */
  1113.     offset = 0;
  1114.     /* Round size down to integral number of codes */
  1115.     size = (size << 3) - (n_bits - 1);
  1116.     }
  1117.     r_off = offset;
  1118.     bits = n_bits;
  1119. #ifdef vax
  1120.     asm( "extzv   r10,r9,(r8),r11" );
  1121. #else /* not a vax */
  1122.     /*
  1123.      * Get to the first byte.
  1124.      */
  1125.     bp += (r_off >> 3);
  1126.     r_off &= 7;
  1127.     /* Get first part (low order bits) */
  1128. #ifdef NO_UCHAR
  1129.     code = ((*bp++ >> r_off) & rmask[8 - r_off]) & 0xff;
  1130. #else
  1131.     code = (*bp++ >> r_off);
  1132. #endif /* NO_UCHAR */
  1133.     bits -= (8 - r_off);
  1134.     r_off = 8 - r_off;        /* now, offset into code word */
  1135.     /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  1136.     if ( bits >= 8 ) {
  1137. #ifdef NO_UCHAR
  1138.         code |= (*bp++ & 0xff) << r_off;
  1139. #else
  1140.         code |= *bp++ << r_off;
  1141. #endif /* NO_UCHAR */
  1142.         r_off += 8;
  1143.         bits -= 8;
  1144.     }
  1145.     /* high order bits. */
  1146.     code |= (*bp & rmask[bits]) << r_off;
  1147. #endif /* vax */
  1148.     offset += n_bits;
  1149.  
  1150.     return code;
  1151. }
  1152.  
  1153. char *
  1154. rindex(s, c)        /* For those who don't have it in libc.a */
  1155. register char *s, c;
  1156. {
  1157.     char *p;
  1158.     for (p = NULL; *s; s++)
  1159.         if (*s == c)
  1160.         p = s;
  1161.     return(p);
  1162. }
  1163.  
  1164. #ifdef DEBUG
  1165. printcodes()
  1166. {
  1167.     /*
  1168.      * Just print out codes from input file.  For debugging.
  1169.      */
  1170.     code_int code;
  1171.     int col = 0, bits;
  1172.  
  1173.     bits = n_bits = INIT_BITS;
  1174.     maxcode = MAXCODE(n_bits);
  1175.     free_ent = ((block_compress) ? FIRST : 256 );
  1176.     while ( ( code = getcode() ) >= 0 ) {
  1177.     if ( (code == CLEAR) && block_compress ) {
  1178.            free_ent = FIRST - 1;
  1179.            clear_flg = 1;
  1180.     }
  1181.     else if ( free_ent < maxmaxcode )
  1182.         free_ent++;
  1183.     if ( bits != n_bits ) {
  1184.         fprintf(stderr, "\nChange to %d bits\n", n_bits );
  1185.         bits = n_bits;
  1186.         col = 0;
  1187.     }
  1188.     fprintf(stderr, "%5d%c", code, (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  1189.     }
  1190.     putc( '\n', stderr );
  1191.     exit( 0 );
  1192. }
  1193.  
  1194. code_int sorttab[1<<BITS];    /* sorted pointers into htab */
  1195.  
  1196. dump_tab()    /* dump string table */
  1197. {
  1198.     register int i, first;
  1199.     register ent;
  1200. #define STACK_SIZE    15000
  1201.     int stack_top = STACK_SIZE;
  1202.     register c;
  1203.  
  1204.     if(do_decomp == 0) {    /* compressing */
  1205.     register int flag = 1;
  1206.  
  1207.     for(i=0; i<hsize; i++) {    /* build sort pointers */
  1208.         if((long)htabof(i) >= 0) {
  1209.             sorttab[codetabof(i)] = i;
  1210.         }
  1211.     }
  1212.     first = block_compress ? FIRST : 256;
  1213.     for(i = first; i < free_ent; i++) {
  1214.         fprintf(stderr, "%5d: \"", i);
  1215.         de_stack[--stack_top] = '\n';
  1216.         de_stack[--stack_top] = '"';
  1217.         stack_top = in_stack((htabof(sorttab[i])>>maxbits)&0xff, 
  1218.                                      stack_top);
  1219.         for(ent=htabof(sorttab[i]) & ((1<<maxbits)-1);
  1220.             ent > 256;
  1221.             ent=htabof(sorttab[ent]) & ((1<<maxbits)-1)) {
  1222.             stack_top = in_stack(htabof(sorttab[ent]) >> maxbits,
  1223.                         stack_top);
  1224.         }
  1225.         stack_top = in_stack(ent, stack_top);
  1226.         fwrite( &de_stack[stack_top], 1, STACK_SIZE-stack_top, stderr);
  1227.            stack_top = STACK_SIZE;
  1228.     }
  1229.    } else if(!debug) {    /* decompressing */
  1230.  
  1231.        for ( i = 0; i < free_ent; i++ ) {
  1232.        ent = i;
  1233.        c = tab_suffixof(ent);
  1234.        if ( isascii(c) && isprint(c) )
  1235.            fprintf( stderr, "%5d: %5d/'%c'  \"",
  1236.                ent, tab_prefixof(ent), c );
  1237.        else
  1238.            fprintf( stderr, "%5d: %5d/\\%03o \"",
  1239.                ent, tab_prefixof(ent), c );
  1240.        de_stack[--stack_top] = '\n';
  1241.        de_stack[--stack_top] = '"';
  1242.        for ( ; ent != NULL;
  1243.            ent = (ent >= FIRST ? tab_prefixof(ent) : NULL) ) {
  1244.            stack_top = in_stack(tab_suffixof(ent), stack_top);
  1245.        }
  1246.        fwrite( &de_stack[stack_top], 1, STACK_SIZE - stack_top, stderr );
  1247.        stack_top = STACK_SIZE;
  1248.        }
  1249.     }
  1250. }
  1251.  
  1252. int
  1253. in_stack(c, stack_top)
  1254.     register c, stack_top;
  1255. {
  1256.     if ( (isascii(c) && isprint(c) && c != '\\') || c == ' ' ) {
  1257.         de_stack[--stack_top] = c;
  1258.     } else {
  1259.         switch( c ) {
  1260.         case '\n': de_stack[--stack_top] = 'n'; break;
  1261.         case '\t': de_stack[--stack_top] = 't'; break;
  1262.         case '\b': de_stack[--stack_top] = 'b'; break;
  1263.         case '\f': de_stack[--stack_top] = 'f'; break;
  1264.         case '\r': de_stack[--stack_top] = 'r'; break;
  1265.         case '\\': de_stack[--stack_top] = '\\'; break;
  1266.         default:
  1267.          de_stack[--stack_top] = '0' + c % 8;
  1268.          de_stack[--stack_top] = '0' + (c / 8) % 8;
  1269.          de_stack[--stack_top] = '0' + c / 64;
  1270.          break;
  1271.         }
  1272.         de_stack[--stack_top] = '\\';
  1273.     }
  1274.     return stack_top;
  1275. }
  1276. #endif /* DEBUG */
  1277.  
  1278. writeerr()
  1279. {
  1280.     perror ( ofname );
  1281.     unlink ( ofname );
  1282.     exit ( 1 );
  1283. }
  1284.  
  1285. copystat(ifname, ofname)
  1286. char *ifname, *ofname;
  1287. {
  1288. #ifdef unix
  1289.     struct stat statbuf;
  1290.     int mode;
  1291.     time_t timep[2];
  1292.  
  1293.     fclose(stdout);
  1294.     if (stat(ifname, &statbuf)) {        /* Get stat on input file */
  1295.     perror(ifname);
  1296.     return;
  1297.     }
  1298.     if ((statbuf.st_mode & S_IFMT/*0170000*/) != S_IFREG/*0100000*/) {
  1299.     if(quiet)
  1300.             fprintf(stderr, "%s: ", ifname);
  1301.     fprintf(stderr, " -- not a regular file: unchanged");
  1302.     exit_stat = 1;
  1303.     } else if (statbuf.st_nlink > 1) {
  1304.     if(quiet)
  1305.             fprintf(stderr, "%s: ", ifname);
  1306.     fprintf(stderr, " -- has %d other links: unchanged",
  1307.         statbuf.st_nlink - 1);
  1308.     exit_stat = 1;
  1309.     } else if (exit_stat == 2 && (!force)) { /* No compression: remove file.Z */
  1310.     if(!quiet)
  1311.         fprintf(stderr, " -- file unchanged");
  1312.     } else {            /* ***** Successful Compression ***** */
  1313.     exit_stat = 0;
  1314.     mode = statbuf.st_mode & 07777;
  1315.     if (chmod(ofname, mode))        /* Copy modes */
  1316.         perror(ofname);
  1317.     chown(ofname, statbuf.st_uid, statbuf.st_gid);    /* Copy ownership */
  1318.     timep[0] = statbuf.st_atime;
  1319.     timep[1] = statbuf.st_mtime;
  1320.     utime(ofname, timep);    /* Update last accessed and modified times */
  1321.     if (unlink(ifname))    /* Remove input file */
  1322.         perror(ifname);
  1323.     if(!quiet)
  1324.         fprintf(stderr, " -- replaced with %s", ofname);
  1325.     return;        /* Successful return */
  1326.     }
  1327.  
  1328.     /* Unsuccessful return -- one of the tests failed */
  1329.     if (unlink(ofname))
  1330.     perror(ofname);
  1331. #endif
  1332. }
  1333. /*
  1334.  * This routine returns 1 if we are running in the foreground and stderr
  1335.  * is a tty.
  1336.  */
  1337. #ifdef unix
  1338. foreground()
  1339. {
  1340.     if(bgnd_flag) {    /* background? */
  1341.         return(0);
  1342.     } else {            /* foreground */
  1343.         if(isatty(2)) {        /* and stderr is a tty */
  1344.             return(1);
  1345.         } else {
  1346.             return(0);
  1347.         }
  1348.     }
  1349. }
  1350. #endif
  1351.  
  1352. onintr ( )
  1353. {
  1354.     unlink ( ofname );
  1355.     exit ( 1 );
  1356. }
  1357.  
  1358. oops ( )    /* wild pointer -- assume bad input */
  1359. {
  1360.     if ( do_decomp == 1 ) 
  1361.         fprintf ( stderr, "uncompress: corrupt input\n" );
  1362.     unlink ( ofname );
  1363.     exit ( 1 );
  1364. }
  1365.  
  1366. cl_block ()        /* table clear for block compress */
  1367. {
  1368.     register long int rat;
  1369.  
  1370.     checkpoint = in_count + CHECK_GAP;
  1371. #ifdef DEBUG
  1372.     if ( debug ) {
  1373.             fprintf ( stderr, "count: %ld, ratio: ", in_count );
  1374.              prratio ( stderr, in_count, bytes_out );
  1375.         fprintf ( stderr, "\n");
  1376.     }
  1377. #endif /* DEBUG */
  1378.  
  1379.     if(in_count > 0x007fffff) {    /* shift will overflow */
  1380.     rat = bytes_out >> 8;
  1381.     if(rat == 0) {        /* Don't divide by zero */
  1382.         rat = 0x7fffffff;
  1383.     } else {
  1384.         rat = in_count / rat;
  1385.     }
  1386.     } else {
  1387.     rat = (in_count << 8) / bytes_out;    /* 8 fractional bits */
  1388.     }
  1389.     if ( rat > ratio ) {
  1390.     ratio = rat;
  1391.     } else {
  1392.     ratio = 0;
  1393. #ifdef DEBUG
  1394.     if(verbose)
  1395.         dump_tab();    /* dump string table */
  1396. #endif
  1397.      cl_hash ( (count_int) hsize );
  1398.     free_ent = FIRST;
  1399.     clear_flg = 1;
  1400.     output ( (code_int) CLEAR );
  1401. #ifdef DEBUG
  1402.     if(debug)
  1403.             fprintf ( stderr, "clear\n" );
  1404. #endif /* DEBUG */
  1405.     }
  1406. }
  1407.  
  1408. cl_hash(hsize)        /* reset code table */
  1409.     register count_int hsize;
  1410. {
  1411. #ifndef XENIX_16    /* Normal machine */
  1412.     register count_int *htab_p = htab+hsize;
  1413. #else
  1414.     register j;
  1415.     register long k = hsize;
  1416.     register count_int *htab_p;
  1417. #endif
  1418.     register long i;
  1419.     register long m1 = -1;
  1420.  
  1421. #ifdef XENIX_16
  1422.     for(j=0; j<=8 && k>=0; j++,k-=8192) {
  1423.     i = 8192;
  1424.     if(k < 8192) {
  1425.         i = k;
  1426.     }
  1427.     htab_p = &(htab[j][i]);
  1428.     i -= 16;
  1429.     if(i > 0) {
  1430. #else
  1431.     i = hsize - 16;
  1432. #endif
  1433.      do {                /* might use Sys V memset(3) here */
  1434.         *(htab_p-16) = m1;
  1435.         *(htab_p-15) = m1;
  1436.         *(htab_p-14) = m1;
  1437.         *(htab_p-13) = m1;
  1438.         *(htab_p-12) = m1;
  1439.         *(htab_p-11) = m1;
  1440.         *(htab_p-10) = m1;
  1441.         *(htab_p-9) = m1;
  1442.         *(htab_p-8) = m1;
  1443.         *(htab_p-7) = m1;
  1444.         *(htab_p-6) = m1;
  1445.         *(htab_p-5) = m1;
  1446.         *(htab_p-4) = m1;
  1447.         *(htab_p-3) = m1;
  1448.         *(htab_p-2) = m1;
  1449.         *(htab_p-1) = m1;
  1450.         htab_p -= 16;
  1451.     } while ((i -= 16) >= 0);
  1452. #ifdef XENIX_16
  1453.     }
  1454.     }
  1455. #endif
  1456.         for ( i += 16; i > 0; i-- )
  1457.         *--htab_p = m1;
  1458. }
  1459.  
  1460. prratio(stream, num, den)
  1461. FILE *stream;
  1462. long int num, den;
  1463. {
  1464.     register int q;            /* Doesn't need to be long */
  1465.  
  1466.     if(num > 214748L) {        /* 2147483647/10000 */
  1467.         q = num / (den / 10000L);
  1468.     } else {
  1469.         q = 10000L * num / den;        /* Long calculations, though */
  1470.     }
  1471.     if (q < 0) {
  1472.         putc('-', stream);
  1473.         q = -q;
  1474.     }
  1475.     fprintf(stream, "%d.%02d%%", q / 100, q % 100);
  1476. }
  1477.  
  1478. version()
  1479. {
  1480.     fprintf(stderr, "%s\n", rcs_ident);
  1481.     fprintf(stderr, "Options: ");
  1482. #ifdef vax
  1483.     fprintf(stderr, "vax, ");
  1484. #endif
  1485. #ifdef NO_UCHAR
  1486.     fprintf(stderr, "NO_UCHAR, ");
  1487. #endif
  1488. #ifdef SIGNED_COMPARE_SLOW
  1489.     fprintf(stderr, "SIGNED_COMPARE_SLOW, ");
  1490. #endif
  1491. #ifdef XENIX_16
  1492.     fprintf(stderr, "XENIX_16, ");
  1493. #endif
  1494. #ifdef COMPATIBLE
  1495.     fprintf(stderr, "COMPATIBLE, ");
  1496. #endif
  1497. #ifdef DEBUG
  1498.     fprintf(stderr, "DEBUG, ");
  1499. #endif
  1500. #ifdef BSD4_2
  1501.     fprintf(stderr, "BSD4_2, ");
  1502. #endif
  1503.     fprintf(stderr, "BITS = %d\n", BITS);
  1504. }
  1505.  
  1506. /*
  1507.  *    Get the size of the file.  Although this is also possible on
  1508.  *    the Amiga, I have not yet implemented this as it is apparently
  1509.  *    used only to adapt the algorithm to make it more efficient for
  1510.  *    small files.  For files on the standard input, the file size
  1511.  *    is unknown, and 100000 is assumed, so we use that value here.
  1512.  *    Fred Fish  14-Jan-86
  1513.  */
  1514.  
  1515. long getfilesize (name)
  1516. char *name;
  1517. {
  1518. #ifdef unix
  1519.     struct stat statbuf;
  1520.  
  1521.     stat ( *fileptr, &statbuf );
  1522.     return (statbuf.st_size);
  1523. #else
  1524.     return (100000);
  1525. #endif
  1526. }
  1527.  
  1528. #ifndef unix
  1529. perror (arg)
  1530. char *arg;
  1531. {
  1532.     if (arg && *arg) {
  1533.         fprintf (stderr, "%s: ", arg);
  1534.     }
  1535.     fprintf (stderr, "<unknown error>\n");
  1536. }
  1537. #endif
  1538.